#include "tableinfo.h"
#include "fieldinfo.h"

CXTableInfo::CXTableInfo(LPCSTR lpszName)
{
    m_strTableName.clear();
    m_strTableName = lpszName;
}

CXTableInfo::~CXTableInfo(void)
{
    m_lstField.clear();
    m_strTableName.clear();
}

LPCSTR CXTableInfo::GetName()
{
    return m_strTableName.c_str();
}

HRESULT CXTableInfo::Add(IFieldInfo* pFieldInfo)
{
    LPCSTR lpszName = pFieldInfo->GetName();
    if (lpszName != NULL) {
        TableStructIter it = m_lstField.find(lpszName);
        if (it != m_lstField.end()) {
            return S_OK;
        }
        return pFieldInfo->QueryInterface(IID_IFieldInfo, (void**)&m_lstField[lpszName]);
    }

    return E_FAIL;
}

HRESULT CXTableInfo::Remove(LPCSTR lpszFieldName)
{
    TableStructIter it = m_lstField.find(lpszFieldName);
    if (it != m_lstField.end()) {
        m_lstField.erase(it);
    }

    return S_OK;
}

HRESULT CXTableInfo::Remove(unsigned int nIndex)
{
    TableStructIter it = m_lstField.begin();
    std::advance(it, nIndex);
    if (it != m_lstField.end()) { }
    return S_OK;
}

ULONG CXTableInfo::GetFieldCount()
{
    return m_lstField.size();
}

HRESULT CXTableInfo::GetField(UINT nIndex, IFieldInfo** pField)
{
    TableStructConstIter it = m_lstField.begin();
    std::advance(it, nIndex);
    if (it != m_lstField.end()) {
        return it->second->QueryInterface(IID_IFieldInfo, (void**)pField);
    }

    return S_OK;
}

HRESULT CXTableInfo::GetField(LPCSTR lpszName, IFieldInfo** pField)
{
    TableStructConstIter it = m_lstField.find(lpszName);
    if (it != m_lstField.end()) {
        return it->second->QueryInterface(IID_IFieldInfo, (void**)pField);
    }

    return E_FAIL;
}

HRESULT CXTableInfo::CreateField(IFieldInfo** pField)
{
    return CXFieldInfo::CreateInstance(pField);
}

HRESULT CXTableInfo::CreateInstance(LPCSTR lpszName, ITableInfo** ppTableInfo)
{
    CXTableInfo* p = ALLOC_NEW CXTableInfo(lpszName);
    rc_error(p != NULL, E_FAIL);
    return p->QueryInterface(IID_ITableInfo, (void**)ppTableInfo);
}
